﻿using System;
using System.Windows.Forms;
using ReadWriteini;
using HandleSign.Models;
using HandleSign.DataBase.AfterClass;
using System.Data.SqlClient;
using System.Data;
using ServerPA.CompletPort.Util;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Timers;
using System.Diagnostics;

namespace HandleSign
{
    public partial class Form1 : Form
    {
        public static List<SystemDataSetModel> sdsModel; // 系 统参数设置
        public static BaseInfo baseInfoModel; // 基础信息
        public static List<TimeInfo> timeInfoList;
        SignClient signClient;
        public Form1()
        {
            InitializeComponent();
        }
        
        public static string connstr;   //Digiin
        public static string connPhoneSign;

        private void Form1_Load(object sender, EventArgs e){

            Stopwatch sw = new Stopwatch();
            sw.Start(); 
            //*******************
            ReadWriteIni getMessage = new ReadWriteIni();
            connstr = getMessage.GetConnetStr(1); //获取本地保存的数据库连接信息
            connPhoneSign = getMessage.GetConnetStr(2); 

            signClient = new SignClient();
            sdsModel = SystemDataSet.GetSet(Form1.connPhoneSign); //配置设置参数
            //baseInfoModel = SystemDataSet.GetBaseInfo(Form1.connstr); //查询所有教室 并保存在内存里
            timeInfoList = SystemDataSet.GetTime(Form1.connstr); //上下课时间

            try
            {
                SqlDependency.Stop(connstr);
                SqlDependency.Stop(connPhoneSign);
                SqlDependency.Start(connstr);
                SqlDependency.Start(connPhoneSign);
                
                // 添加监听
                UpdateSet();
                //UpdateTerminal();
                UpdateTime();
            }
            catch (Exception ex)
            {
                LogUtil.LogToFile(ex, "Form1");
            }

            Button btn = ((Button)(this.Controls.Find("button1", false)[0]));
            //btn.PerformClick();
            btn.Text = "正在处理中";
            btn.Enabled = false;
            signClient.client();
            btn.Text = "处理完毕";
            btn.Enabled = true;

            sw.Stop();

            
            LogUtil.SaveLog(sw.ElapsedMilliseconds+"");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled == false)
            {
                timer1.Enabled = true;
            }

            Button btn = sender as Button;//按钮本身
            btn.Text = "正在处理中";
            btn.Enabled = false;
            signClient.client();
            btn.Text = "处理完毕";
            btn.Enabled = true;

        }




        //定时器
        private void timer1_Tick(object sender, EventArgs e)
        {
           timer1.Enabled = false;
            //signClient.client();

            //------------------------
            if (signClient.isFinish)
            {
                signClient.client();
                Button btn = ((Button)(this.Controls.Find("button1", false)[0])); 
                btn.Text = "自动处理完毕";
            }
            else
            {
                signClient.isTimerHasStarted = true;
            }
            //------------------------
            timer1.Enabled = true;//如果不先把enabled设置成false对话框会一直弹下去
        }


        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        //private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //}
        
        //3/30
        //监听
        public void UpdateSet()
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connPhoneSign))
                {
                    using (SqlCommand command = new SqlCommand("SELECT [set_StartEvenNum],[set_TimeThresHold],[set_TerminalCheNum],[set_TerminalStuChe],[set_TimeSetS],[set_TimeSetE] FROM [dbo].[P_Set] where set_SgroupId = 2", connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Notification = null;        //确认非之前的

                        SqlDependency dependency = new SqlDependency(command);
                        
                        dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                        connection.Open();
                        command.ExecuteNonQuery();
                        connection.Close();

                        sdsModel = SystemDataSet.GetSet(connPhoneSign); //配置设置参数
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.LogToFile(ex, "Form1");
            }
        }

        //触发
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            try
            {
                ((SqlDependency)sender).OnChange -= dependency_OnChange;
                UpdateSet();
            }
            catch (Exception ex)
            {
                LogUtil.LogToFile(ex, "Form1");
            }
        }

        //3/30
        //监听
        //public void UpdateTerminal()
        //{
        //    try
        //    {
        //        using (SqlConnection connection = new SqlConnection(connPhoneSign))
        //        {
        //            using (SqlCommand command = new SqlCommand("select [At_RoomId],[At_TerminalId] from [dbo].[P_AgentTerminal] where At_RoomId  != 0", connection))
        //            {
        //                command.CommandType = CommandType.Text;
        //                command.Notification = null;        //确认非之前的

        //                SqlDependency dependency_Terminal = new SqlDependency(command);
        //                dependency_Terminal.OnChange += new OnChangeEventHandler(dependency_OnChange_Terminal);
        //                connection.Open();
        //                command.ExecuteNonQuery();
        //                connection.Close();

        //                baseInfoModel = SystemDataSet.GetBaseInfo(connPhoneSign); //查询所有教室 并保存在内存里
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtil.LogToFile(ex, "Form1");
        //    }
        //}

        ////触发
        //private void dependency_OnChange_Terminal(object sender, SqlNotificationEventArgs e)
        //{
        //    try
        //    {
        //        ((SqlDependency)sender).OnChange -= dependency_OnChange_Terminal;
        //        UpdateTerminal();
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtil.LogToFile(ex, "Form1");
        //    }
        //}


        //3/30
        //监听
        public void UpdateTime()
        {
            try
            {
                ReadWriteIni getMessage = new ReadWriteIni();
                string ConnetStr3 = getMessage.GetConnetStr(1); //获取本地保存的数据库连接信息
                SqlDependency.Stop(ConnetStr3);
                SqlDependency.Start(ConnetStr3);

                using (SqlConnection connection = new SqlConnection(ConnetStr3))
                {
                    using (SqlCommand command = new SqlCommand("SELECT  [time_num],[time_SgroupId],[time_Stime],[time_Etime],[time_Compus] FROM [dbo].[R_Times]   where time_view = 1", connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Notification = null;        //确认非之前的

                        SqlDependency dependency_Time = new SqlDependency(command);
                        dependency_Time.OnChange += new OnChangeEventHandler(dependency_OnChange_Time);
                        connection.Open();
                        command.ExecuteNonQuery();
                        connection.Close();

                        timeInfoList = SystemDataSet.GetTime(Form1.connstr); //查询所有教室 并保存在内存里
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.LogToFile(ex, "Form1");
            }
        }

        //触发
        private void dependency_OnChange_Time(object sender, SqlNotificationEventArgs e)
        {
            try
            {
                ((SqlDependency)sender).OnChange -= dependency_OnChange_Time;
                UpdateTime();
            }
            catch (Exception ex)
            {
                LogUtil.LogToFile(ex, "Form1");
            }
        }


        string strFolderPath = Environment.CurrentDirectory;

        private void button2_Click(object sender, EventArgs e)
        {
            DeleteFolder(strFolderPath + "\\Log");
        }
        
        private static System.Timers.Timer aTimer;

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.CheckState == CheckState.Checked)
            {
                //double day = 1000*60*60*24;
                double day = 1000;

                //实例化Timer类，设置间隔时间为10000毫秒； 
                aTimer = new System.Timers.Timer(15 * day);

                //注册计时器的事件
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

                //设置时间间隔为2秒（2000毫秒），覆盖构造函数设置的间隔
                aTimer.Interval = 15 * day;

                //设置是执行一次（false）还是一直执行(true)，默认为true
                aTimer.AutoReset = true;

                //开始计时
                aTimer.Enabled = true;
            }
            else { 
                aTimer.Enabled = false;
            }
        }

        //指定Timer触发的事件
        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            DeleteFolder(strFolderPath + "\\Log");
        }

        //定时删除log
        private void timer2_Tick(object sender, EventArgs e)
        {
            DeleteFolder(strFolderPath + "\\Log");
        }


        /// 清空指定的文件夹，但不删除文件夹
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0)
                    {
                        DeleteFolder(d1.FullName);////递归删除子文件夹
                    }
                    Directory.Delete(d);
                }
            }
        }

    }
}